<?php
    include('../lib/conn.php');
    
    // 接收前端发送的数据
    $username = $_REQUEST['username'];
    $password = $_REQUEST['password'];
    $email = $_REQUEST['email'];
    $phone = $_REQUEST['phone'];

    echo "$username , $password , $email , $phone";




    $sql = "select * from reg where name='$username'";  //查询语句

    $result = $mysqli->query($sql);  //执行sql语句
    var_dump($result);
    $num=$result->num_rows;
    echo $num;
    if($num>0){
        echo '<script>alert("用户名已存在");</script>';
        echo '<script>location.href="../html/注册.html";</script>';
        $mysqli->close(); 
        die; //如果用户名存在 代码不再往下执行
    }
    if($username==''||$password==''||$email==''||$phone==''){
        echo '<script>alert("注册失败，用户名、密码、邮箱或手机号码不能为空！！")</script>';
        echo '<script>location.href="../html/注册.html";</script>';
    }
    if(strlen($username)<6||strlen($password)<6){
        echo '<script>alert("注册失败，用户名或密码格式错误！！")</script>';
        echo '<script>location.href="../html/注册.html";</script>';
    }
    $pattern1="/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";
    $pattern2="/^1[34578]\d{9}$/";
    if(!preg_match($pattern1, $email, $matches)){
        echo '<script>alert("注册失败，邮箱或手机格式错误！！1")</script>';
        echo '<script>location.href="../html/注册.html";</script>';
    } 
    if(!preg_match($pattern2, $phone, $matches)){
        echo '<script>alert("注册失败，邮箱或手机格式错误！！3")</script>';
        echo '<script>location.href="../html/注册.html";</script>';
    }
    



    $insSql="INSERT INTO `reg` (`name`,`password`,`email`,`phone`) VALUES ('$username','$password','$email','$phone')";
    $res = $mysqli->query($insSql);//执行插入语句
    
    var_dump($res);
    print_r($insSql);
    if($res){
        echo '<script>alert("注册成功")</script>';
        echo '<script>location.href="../html/首页.html"</script>';
    }else{
        echo '<script>alert("注册失败")</script>';
        echo '<script>location.href="../html/注册.html";</script>';
    }
    

    $mysqli->close();

?>